/**
 * @author:linjiye
 * @date: 2024/01/14
 * @desc: AI原创模块接口定义
 **/

import {createApi} from "@reduxjs/toolkit/query/react";
import useBaseQuery from "@/hooks/useBaseQuery";
import { stringify } from "qs";

export const aiOriginalityApi = createApi({
    reducerPath:'aiOriginalityApi',
    baseQuery:useBaseQuery('mm'),
    tagTypes: ['itemList','parentList'],
    endpoints(build) {
        return {
            getGroupTemplateList:build.query({
                query:(data:any) => {
                    return {
                        url: 'aicreation/getGroupTemplateList',
                        method:"get",
                        params:data,
                        openErrMessage: true
                    }
                },
            }),
            // ttp://192.168.200.122:3200/jeecgboot/mm/aicreation/get_template_list?promptCate=3&versionType=1&_t=1736822463441
            getTemplateList:build.query({
                query:(data:any) => {
                    return {
                        url: 'aicreation/get_template_list',
                        method:"get",
                        params:data,
                        openErrMessage: true
                    }
                },
            }),
            // http://192.168.200.122:3200/jeecgboot/mm/mmVpGroup/parentList?type=1&_t=1736835652507
            getParentList:build.query({
                query:(data:any) => {
                    return {
                        url: 'mmVpGroup/parentList',
                        method:"get",
                        params:data,
                        openErrMessage: true
                    }
                },
                providesTags: ['parentList'],
            }),
            // http://192.168.200.122:3200/jeecgboot/mm/mmVpGroup/add
            addGroup: build.mutation({
                query(data) {
                    return {
                        url: 'mmVpGroup/add',
                        method: "post",
                        body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['parentList','itemList'],
            }),
            // mm/mmVpGroup/delete
            deleteGroup: build.mutation({
                query(data) {
                    return {
                        // url:'mmVpGroup/delete?id='+data.ids,
                        url:'mmVpGroup/deleteBatch?ids='+data.ids,
                        method: "delete",
                        // body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['parentList'],
            }),
            // mm/mmVpGroup/edit
            editGroup: build.mutation({
                query(data) {
                    return {
                        url:'mmVpGroup/edit',
                        method: "put",
                        body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['parentList'],
            }),
            // http://192.168.200.122:3200/jeecgboot/mm/mmVpGroup/itemList?types=1,2&_t=1736835652444
            getItemList:build.query({
                query:(data:any) => {
                    return {
                        url: 'mmVpGroup/itemList',
                        method:"get",
                        params:data,
                        openErrMessage: true
                    }
                },
                providesTags: ['itemList'],
            }),
            // http://192.168.10.122:3200/jeecgboot/mm/mmVpGroup/edit
            editProduct: build.mutation({
                query(data) {
                    return {
                        url:'mmVpGroup/edit',
                        method: "put",
                        body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['itemList'],
            }),
            // http://192.168.10.122:3200/jeecgboot/mm/mmVpGroup/delete?id=1888466327792791553
            deleteProduct: build.mutation({
                query(data) {
                    return {
                        // url:'mmVpGroup/delete?id='+data.ids,
                        url:'mmVpGroup/deleteBatch?id='+data.ids,
                        method: "delete",
                        // body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['itemList'],
            }),
            // mm/mmVpGroup/batchGroup
            batchGroup: build.mutation({
                query(data) {
                    return {
                        url:'mmVpGroup/batchGroup',
                        method: "post",
                        body: data,
                        openErrMessage: true
                    }
                },
                invalidatesTags: ['parentList','itemList'],
            }),
            // http://192.168.200.122:3200/jeecgboot/mm/mmVpGroup/profitModelInfo?id=1828334302377635841
            profitModelInfo:build.mutation({
                query:(data:any) => {
                    return {
                        url: 'mmVpGroup/profitModelInfo?id='+data.id,
                        method:"post",
                        // body:JSON.stringify(data),
                        openErrMessage: true
                    }
                },
            }),

            // http://192.168.200.122:3200/jeecgboot/mm/aicreation/get_topdata_by_listcode?listcode=douyin_hotsearch&_t=1736836506456
            getTopDataByListCode:build.query({
                query:(data:any) => {
                    return {
                        url: 'aicreation/get_topdata_by_listcode',
                        method:"get",
                        params:data,
                        openErrMessage: true
                    }
                },
            }),
            // http://192.168.200.122:3200/jeecgboot/mm/mmContentManagePub/add
            mmContentManagePubAdd: build.mutation({
                query(data) {
                    return {
                        url:'mmContentManagePub/add',
                        method:"post",
                        body:data,
                        openErrMessage: true
                    }
                },
                // transformResponse(baseQueryReturnValue, meta, arg) {
                //     return baseQueryReturnValue.data;
                // },
            }),
            // http://192.168.200.122:3200/jeecgboot/common/check/sensitive-content-detection
            sensitiveContentDetection: build.mutation({
                query(data) {
                    return {
                        url:'check/sensitive-content-detection',
                        method:"post",
                        body:data,
                        openErrMessage: true
                    }
                },
            }),
            // http:/192.168.10122:3200/jeecgboot/mm/aicreation/reduce_similarity
            reduceSimilarity: build.mutation({
                query(data) {
                    return {
                        url:'aicreation/reduce_similarity',
                        method:"post",
                        body:data,
                        openErrMessage: true
                    }
                },
            }),
            getStreamWriting_by_template:build.mutation({
                // query:(data:any) => {
                //     return {
                //         url: 'aicreation/writing_by_template',
                //         method:"post",
                //         body:data,
                //         openErrMessage: true,
                //         stream:true,
                //
                //     }
                // },
                // transformResponse(baseQueryReturnValue, meta, arg){
                //     console.log(baseQueryReturnValue,'---');
                // }
                // queryFn: async (_, { signal }) => {
                //     try {
                //         const response = await fetch('aicreation/writing_by_template', { signal });
                //         if (!response.ok) {
                //             throw new Error(`HTTP error! status: ${response.status}`);
                //         }
                //
                //         const reader = response.body.getReader();
                //         const decoder = new TextDecoder('utf-8');
                //         let allChunks = [];
                //
                //         while (true) {
                //             const { done, value } = await reader.read();
                //             if (done) {
                //                 break;
                //             }
                //             const chunk = decoder.decode(value, { stream: true });
                //             allChunks.push(chunk);
                //         }
                //
                //         return { data: allChunks };
                //     } catch (error) {
                //         return { error: error.message };
                //     }
                // },
                queryFn: async (body, { signal }) => {
                    try {
                        const response = await fetch('http://kyle1.natapp1.cc/mm/aicreation/writing_by_template', {
                            method: 'POST',
                            headers: {
                                'Accept': 'text/event-stream',
                                'Content-Type': 'application/json',
                                'x-access-token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDA1NzgxMzksInVzZXJuYW1lIjoieWl6dW9taW4ifQ.GSwIxpSqHd-Li2vS7aQ3WG48m7xxy_mGzgkZB2tLa64'
                            },
                            body: JSON.stringify(body),
                            signal
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }

                        const reader = response.body.getReader();
                        const decoder = new TextDecoder('utf-8');
                        let allChunks = [];
                        let str = ''

                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) {
                                break;
                            }
                            console.log(111);
                            const chunk = decoder.decode(value, { stream: true });
                            // let res = JSON.parse(chunk)
                            // console.log('11111',res);
                            //         if (res.status == 'success') {
                            //             let txt = res.text.replace(/(<br\/>)|(<br)/g, '');
                            //             let l = [...list]
                            //             l[index - 1].content = txt
                            //             setList(l)
                            //         } else {
                            //             resData.close();
                            //         }
                            // chunk = chunk.replace(/\\\//g, '/');
                            console.log(chunk);
                            allChunks.push(chunk);
                        }

                        return { data: allChunks };
                    } catch (error) {
                        return { error: error.message };
                    }
                },
            }),
        }
    }
});

export const aiOriginalityCommonApi = createApi({
    reducerPath:'aiOriginalityCommonApi',
    baseQuery:useBaseQuery('common'),
    endpoints(build) {
        return {
            // http://192.168.200.122:3200/jeecgboot/common/check/sensitive-content-detection
            sensitiveContentDetection: build.mutation({
                query(data) {
                    return {
                        url:'check/sensitive-content-detection',
                        method:"post",
                        body:data,
                        openErrMessage: true
                    }
                },
            })
        }
    }
});

export const {
    useGetGroupTemplateListQuery,
    useGetTemplateListQuery,
    useGetParentListQuery,
    useAddGroupMutation,
    useDeleteGroupMutation,
    useEditGroupMutation,
    useGetItemListQuery,
    useEditProductMutation,
    useDeleteProductMutation,
    useBatchGroupMutation,
    useProfitModelInfoMutation,
    useGetTopDataByListCodeQuery,
    useGetStreamWriting_by_templateMutation,
    useMmContentManagePubAddMutation,
    useReduceSimilarityMutation
} = aiOriginalityApi;

export const {
    useSensitiveContentDetectionMutation,
} = aiOriginalityCommonApi;
